﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace OCDStudio.SqlAzureBackup.Client.Code
{
    public static class Extensions
    {
        public static string AsXmlString(this object self)
        {
            XmlSerializer ser = new XmlSerializer(self.GetType());
            using (var str = new MemoryStream())
            {
                ser.Serialize(str, self);
                str.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(str))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        public static T AsObjectFromXml<T>(this string self)
        {
            if (string.IsNullOrEmpty(self)) return default(T);
            XmlSerializer ser = new XmlSerializer(typeof(T));
            T toReturn = (T)ser.Deserialize(new StringReader(self));
            return toReturn;
        }
    }
}
